package com.micro.ai.models.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.micro.ai.commons.domain.ApiResponse;
import com.micro.ai.models.entity.FineTunedModel;
import com.micro.ai.models.service.FineTunedModelService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;

/**
 * 微调模型控制器
 * 
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@RestController
@RequestMapping("/api/fine-tuned-models")
@Tag(name = "微调模型管理", description = "微调模型的增删改查、部署、归档")
public class FineTunedModelController {

    @Autowired
    private FineTunedModelService modelService;

    @PostMapping
    @PreAuthorize("hasRole('ADMIN') or hasAuthority('fine-tuned:model:create')")
    @Operation(summary = "创建微调模型", description = "创建新的微调模型")
    public ApiResponse<FineTunedModel> create(@Valid @RequestBody FineTunedModel model) {
        log.info("创建微调模型请求: tenantId={}, modelName={}", model.getTenantId(), model.getModelName());
        model.setCreatedBy(getCurrentUsername());
        FineTunedModel result = modelService.create(model);
        return ApiResponse.success("创建成功", result);
    }

    @PutMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN') or hasAuthority('fine-tuned:model:update')")
    @Operation(summary = "更新微调模型", description = "更新微调模型信息")
    public ApiResponse<FineTunedModel> update(
            @Parameter(description = "模型ID", required = true) @PathVariable String id,
            @Valid @RequestBody FineTunedModel model) {
        log.info("更新微调模型请求: modelId={}", id);
        
        FineTunedModel result = modelService.update(id, model);
        return ApiResponse.success("更新成功", result);
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN') or hasAuthority('fine-tuned:model:delete')")
    @Operation(summary = "删除微调模型", description = "删除微调模型")
    public ApiResponse<Void> delete(
            @Parameter(description = "模型ID", required = true) @PathVariable String id) {
        log.info("删除微调模型请求: modelId={}", id);
        
        modelService.delete(id);
        return ApiResponse.successVoid("删除成功");
    }

    @GetMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN') or hasRole('USER') or hasAuthority('fine-tuned:model:view')")
    @Operation(summary = "获取微调模型详情", description = "获取微调模型详细信息")
    public ApiResponse<FineTunedModel> getById(
            @Parameter(description = "模型ID", required = true) @PathVariable String id) {
        log.info("查询微调模型详情: modelId={}", id);
        
        FineTunedModel model = modelService.getById(id);
        if (model == null) {
            return ApiResponse.error("404", "微调模型不存在");
        }
        
        return ApiResponse.success(model);
    }

    @GetMapping
    @PreAuthorize("hasRole('ADMIN') or hasRole('USER') or hasAuthority('fine-tuned:model:view')")
    @Operation(summary = "分页查询微调模型", description = "根据条件分页查询微调模型列表")
    public ApiResponse<Page<FineTunedModel>> pageQuery(
            @Parameter(description = "页码", example = "1") @RequestParam(defaultValue = "1") int pageNum,
            @Parameter(description = "每页数量", example = "20") @RequestParam(defaultValue = "20") int pageSize,
            @Parameter(description = "租户ID") @RequestParam(required = false) String tenantId,
            @Parameter(description = "关键词") @RequestParam(required = false) String keyword,
            @Parameter(description = "状态") @RequestParam(required = false) String status) {
        log.info("分页查询微调模型: pageNum={}, pageSize={}", pageNum, pageSize);
        
        Page<FineTunedModel> page = modelService.pageQuery(pageNum, pageSize, tenantId, keyword, status);
        return ApiResponse.success(page);
    }

    @PostMapping("/{id}/deploy")
    @PreAuthorize("hasRole('ADMIN') or hasAuthority('fine-tuned:model:update')")
    @Operation(summary = "部署模型", description = "部署微调模型")
    public ApiResponse<Void> deploy(
            @Parameter(description = "模型ID", required = true) @PathVariable String id) {
        log.info("部署模型请求: modelId={}", id);
        
        modelService.deploy(id);
        return ApiResponse.successVoid("部署成功");
    }

    @PostMapping("/{id}/archive")
    @PreAuthorize("hasRole('ADMIN') or hasAuthority('fine-tuned:model:update')")
    @Operation(summary = "归档模型", description = "归档微调模型")
    public ApiResponse<Void> archive(
            @Parameter(description = "模型ID", required = true) @PathVariable String id) {
        log.info("归档模型请求: modelId={}", id);
        
        modelService.archive(id);
        return ApiResponse.successVoid("归档成功");
    }

    private String getCurrentUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication != null ? authentication.getName() : "system";
    }
}

